package mysql.commands;

import design_patterns.command.Command;
import mysql.Connection;
import mysql.ddl.SqlStrategy;

import java.sql.SQLException;
import java.util.Scanner;

import static com.google.common.base.CaseFormat.LOWER_UNDERSCORE;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static mysql.ddl.SqlStrategy.LOAD_FILE;

/**
 * Created by nuno-rafael-figueiredo on 01-07-2014.
 */
public abstract class SqlCommand extends Command {
    protected final Connection connection;

    private String sql;

    public SqlCommand(Connection connection, SqlStrategy strategy) {
        this.connection = connection;
        if (strategy == LOAD_FILE) {
            Class<? extends SqlCommand> aClass = getClass();
            try(Scanner scanner = new Scanner(aClass.getResourceAsStream(String.format("%s.sql", UPPER_CAMEL.to(LOWER_UNDERSCORE, aClass.getSimpleName()))), "UTF-8")){
            	setSql(String.format(scanner.useDelimiter("\\A").next(), connection.getSchemaName()));
            }
        }
    }

    public SqlCommand(Connection connection, String sql) {
        this.connection = connection;
        this.sql = sql;
    }

    protected void setSql(String sql) {
        this.sql = sql;
    }

    public String getSql() {
        return sql;
    }

    @Override
    public void execute() {
        try {
            System.out.println(getSql());
            connection.execute(getSql());
            finish();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
